package com.islem;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.objects.Kullanici;

public class DosyaIslemleri implements Islemler {
	final String FILE_PATH = "C:\\kullanici\\1.txt";

	@Override
	public Kullanici getKullanici(String username, String password) {
		BufferedReader br = null;
		Kullanici kullanici = null;
		try {
			String line;
			br = new BufferedReader(new FileReader(getFile()));
			while ((line = br.readLine()) != null) {
				String[] kullaniciVeri = line.split(";");
				if (username.equals(kullaniciVeri[0])) {
					if (password.equals(kullaniciVeri[1])) {
						kullanici = new Kullanici();
						kullanici.setUsername(username);
						kullanici.setPassword(password);
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return kullanici;
	}

	@Override
	public boolean yeniKullanici(Kullanici kullanici) {
		boolean kontrol = false;
		try {
			String kullaniciVeri = kullanici.getUsername() + ";"
					+ kullanici.getPassword() + ";" + kullanici.getGizliSoru()
					+ ";" + kullanici.getCevap();

			if (!getFile().exists()) {
				getFile().createNewFile();
			}

			FileWriter fileWritter = new FileWriter(getFile(), true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
			bufferWritter.write(kullaniciVeri);
			bufferWritter.close();
			kontrol = true;
		} catch (IOException e) {
			kontrol = false;
		}
		return kontrol;
	}

	private File getFile() {
		return new File(FILE_PATH);
	}

}
